import 'package:json_annotation/json_annotation.dart';
import 'package:date_format/date_format.dart';

part 'group.g.dart';

///分组类，记录分组信息
@JsonSerializable()
class Group {
  int? id = 0; //ID
  String? name = ""; //分组名称
  List<Account>? list; //分组下账号信息

  Group({this.id, this.name, this.list});

  factory Group.fromJson(Map<String, dynamic> json) => _$GroupFromJson(json);

  Map<String, dynamic> toJson() => _$GroupToJson(this);
}

///记录账号相关信息
/// [list] 为实际账号信息，为key-value方式，其中[list] position 0 固定为名称
/// 名称为账号的唯一标识，多个名称之间不允许共存
@JsonSerializable()
class Account {
  int id = -1; //用户id
  @JsonKey(name: "g_id")
  int gId = -1; //分组id
  @JsonKey(name: "g_name")
  String gName = "";
  int time = 0; //创建时间
  List<AccountState>? list;

  Account() {
    list = [];
  }

  ///判断当前内容是否合法
  ///仅判断文本，都不为空则为true，否则返回false
  bool isValid() {
    if (list!.length == 0) return false;
    //判断value是否为空
    for (AccountState state in list!) {
      if (state.key == null || state.key!.trim() == "") return false;
      if (state.value == null || state.value!.trim() == "") return false;
    }
    return true;
  }

  factory Account.fromJson(Map<String, dynamic> json) =>
      _$AccountFromJson(json);

  Map<String, dynamic> toJson() => _$AccountToJson(this);

  ///获取时间的字符串形式
  String getTimeStr() {
    return formatDate(
        DateTime.fromMillisecondsSinceEpoch(time), [yyyy, '-', mm, '-', dd]);
  }
}

///账号相关信息，除了第一行名称之外的其他内容
@JsonSerializable(includeIfNull: false)
class AccountState {
  String? key;
  String? value;

  AccountState({this.key, this.value});

  factory AccountState.fromJson(Map<String, dynamic> json) =>
      _$AccountStateFromJson(json);

  Map<String, dynamic> toJson() => _$AccountStateToJson(this);
}
